import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, Alert, TouchableOpacity, ScrollView } from 'react-native';
import { Icon, List, ListItem, Button } from 'react-native-elements';
import Loader from './widgets/Loader';
import { clearStorage } from './clientStorage';
import { NavigationActions } from 'react-navigation';
import DeviceInfo from 'react-native-device-info';
import { primaryColor } from './utils';
import Barcode from 'react-native-barcode-builder';

const styles = StyleSheet.create({
  button: {
    paddingTop: 32
  }
});

class MePage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    return {
      title: screenProps.chinese?`设置`:`Settings`,
      tabBarLabel: screenProps.chinese?`设置`:`Settings`,
      tabBarIcon: ({tintColor}) => <Icon name='settings' color={tintColor} size={24}/>
    };
  }
  onSignOut = () => {
    const chinese = this.props.screenProps.chinese;
    Alert.alert(
      chinese?'确定要登出么？':'Aure you sure you want to sign out?',
      null,
      [
        {text: chinese?'取消':'Cancel'},
        {text: chinese?'确定':'OK', onPress: () => {
          clearStorage().then(() => {
            this.props.screenProps.resetStore();
            this.props.navigation.dispatch(NavigationActions.reset({
              index: 0,
              actions: [
                NavigationActions.navigate({routeName: 'Login'})
              ]
            }));
          })
        }},
      ],
    );
  }
  onPrinter = () => this.props.navigation.navigate('Printer')
  render() {
    const chinese = this.props.screenProps.chinese;
    const { worker, loading } = this.props;
    if (!worker||loading) return <Loader/>;

    return (
      <ScrollView>
        <List>
          <ListItem hideChevron leftIcon={{name:'account-circle'}} title={`${worker.firstName} ${worker.lastName}`} subtitle={chinese?'姓名':'Name'}/>
          <ListItem hideChevron leftIcon={{name:'phone'}} title={worker.contact||'n/a'} subtitle={chinese?'电话':'Contact'}/>
        </List>
        <List>
          <ListItem hideChevron title={DeviceInfo.getVersion()} subtitle={chinese?'应用程式版本':'App Version'}/>
        </List>
        <List>
          <ListItem hideChevron title={chinese?'配置打印机':'Configure Printer'} onPress={this.onPrinter}/>
        </List>
        <Barcode value={worker&&`k${worker.displayId}k`} format="CODE128" />
        <View style={styles.button}>
          <Button backgroundColor='white' color='black' title={chinese?'登出':'SIGN OUT'} onPress={this.onSignOut}/>
        </View>
      </ScrollView>
    );
  }
}

export default graphql(gql`
  query MePage {
    worker {
      id
      displayId
      firstName
      lastName
      email
      contact
    }
  }
`, {
  props: ({data:{worker, loading}}) => {
    return {
      worker,
      loading
    };
  }
})(MePage);

